# -*- mode: python, coding: utf-8 -*-

# Copyright (C) 1994  Ling Li
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Library General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


import gobject, gtk
from gtk import *

import os, re, threading, string

from coralftp_globals import *
from site_info import *
from utils import *

RESPONSE_CONNECT = 0

class QuickConnect(gobject.GObject):

    __gsignals__ = {
        'response' :
        (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, (gobject.TYPE_INT,)),
        }

    ATTRS = {'server_addr' : ('ent_server', ''),
             'server_port' : ('spin_port', '21'),
             'username' : ('ent_username', ''),
             'password' : ('ent_password', ''),
             'anonymous' : ('cb_anonymous', False),
             'remote_path' : ('ent_remote_path', ''),
             'remote_charset' : ('ent_remote_charset', 'GBK'),
             'use_pasv' : ('cb_use_pasv', True),
             }

    __paste_from_clipboard = False

    def __init__(self, remote_view):
        self.__gobject_init__()
        self.remote_view = remote_view
        self.coralftp = remote_view.main_window.coralftp
        self.__xml = get_glade_xml('quick_connect')
        self.__xml.signal_autoconnect(self)
        self.__window = self.__xml.get_widget('quick_connect')
        cmb_history = self.__xml.get_widget('cmb_history')
        model = ListStore(gobject.TYPE_STRING, gobject.TYPE_PYOBJECT)
        cmb_history.set_model(model)
        self.__site_manager = self.coralftp.get_site_manager()
        self.__quick_folder = self.__site_manager.find_folder_by_path(
            '/Quick Connect')
        for name, site in self.__quick_folder.items():
            iter = model.append((name, site))
        return

    def on_response(self, obj, resp, *args):
        if resp == RESPONSE_CONNECT:
            check_ok = True
            ent_server = self.__xml.get_widget('ent_server')
            if string.strip(ent_server.get_text()) == '':
                check_ok = False
            self.__site_manager.save()
        if resp in (RESPONSE_CLOSE, RESPONSE_DELETE_EVENT) \
               or resp == RESPONSE_CONNECT and check_ok:
            self.__window.set_modal(False)
            self.__window.hide()
        self.emit('response', resp)
        return
    
    def run(self):
        self.__window.show()
        self.__window.set_modal(True)
        return

    def destroy(self):
        self.__window.destroy()

    def __getattr__(self, name):
        if name == 'site_info':
            site_info = SiteInfo()
            for name, widget_info in QuickConnect.ATTRS.items():
                widget_name, default_value = widget_info
                widget = self.__xml.get_widget(widget_name)
                if isinstance(widget, Entry):
                    value = widget.get_text()
                    if widget.get_visibility():
                        value = string.strip(value)
                    site_info[name] = value
                elif isinstance(widget, CheckButton):
                    site_info[name] = widget.get_property('active')
                else:
                    raise ValueError, name
            site_name = site_info['server_addr']
            if self.__quick_folder.has_key(site_name):
                i = 1
                while self.__quick_folder.has_key("%s%d" % (site_name, i)):
                    i = i + 1
                site_name = "%s%d" % (site_name, i)
            site_info['site_name'] = site_name
            site_info['local_path'] = ''
            return site_info
        else:
            raise ValueError, name
        return
    
    def on_ent_server_insert_text(self, obj, new_text, new_text_length, position, *args):
        if self.__paste_from_clipboard:
            m = ftpurl_parse(new_text)
            if not m: return
            username, password, server, port, path = m
            if server != None:
                entry_server = self.__xml.get_widget('ent_server')
                entry_server.set_text(server)
            spin_port = self.__xml.get_widget('spin_port')
            if port != None:
                spin_port.set_text(port)
            else:
                spin_port.set_text('21')
            entry_username = self.__xml.get_widget('ent_username')
            entry_password = self.__xml.get_widget('ent_password')
            cb_anonymous = self.__xml.get_widget('cb_anonymous')
            if username != None:
                entry_username.set_text(username)
            if password != None:
                entry_password.set_text(password)
            cb_anonymous.set_property('active', not (username or password))
            
            obj.stop_emission('insert-text')
            self.__paste_from_clipboard = False
        return
    
    def on_ent_server_paste_clipboard(self, obj, *args):
        self.__paste_from_clipboard = True
        return

    def on_cb_anonymous_toggled(self, obj, *args):
        anonymous = obj.get_property('active')
        widget = self.__xml.get_widget('ent_username')
        widget.set_property('sensitive', not anonymous)
        widget = self.__xml.get_widget('ent_password')
        widget.set_property('sensitive', not anonymous)
        return

    def on_cmb_history_changed(self, obj, *args):
        iter = obj.get_active_iter()
        model = obj.get_model()
        site = model.get_value(iter, 1)
        for name, widget_info in QuickConnect.ATTRS.items():
            widget_name, default_value = widget_info
            widget = self.__xml.get_widget(widget_name)
            if isinstance(widget, Entry):
                if site.has_key(name):
                    widget.set_text(site[name])
                else:
                    widget.set_text(default_value)
            elif isinstance(widget, CheckButton):
                if site.has_key(name):
                    widget.set_property('active', site[name] == 'True')
                else:
                    widget.set_property('active', default_value) 
            else:
                raise ValueError, name
        return

    def on_btn_add_clicked(self, obj, *args):
        cmb_history = self.__xml.get_widget('cmb_history')
        model = cmb_history.get_model()
        site = self.site_info
        iter = model.prepend((site['site_name'], site))
        cmb_history.set_active_iter(iter)
        self.__site_manager.add_site('/Quick Connect', site)
        return

    def on_btn_remove_clicked(self, obj, *args):
        cmb_history = self.__xml.get_widget('cmb_history')
        model = cmb_history.get_model()
        iter = cmb_history.get_active_iter()
        site = model.get_value(iter, 1)
        model.remove(iter)
        self.__site_manager.delete_site('/Quick Connect/' + site['site_name'])
        return
 
gobject.type_register(QuickConnect)
